/**
 * Copyright (c) 2011 eelpo.com
 * All rights reserved.
 */
package com.eelpo.cmmp.uac.services.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import com.eelpo.cmmp.core.exception.ServiceException;
import com.eelpo.cmmp.uac.dao.IUserManageDao;
import com.eelpo.cmmp.uac.dao.entity.TUser;
import com.eelpo.cmmp.uac.dao.vo.User;
import com.eelpo.cmmp.uac.dao.vo.enumed.AuthMode;
import com.eelpo.cmmp.uac.dao.vo.enumed.Status;
import com.eelpo.cmmp.uac.dao.vo.enumed.YesOrNo;
import com.eelpo.cmmp.uac.services.IUserManageService;
import com.eelpo.common.security.PasswordEncryptor;
import com.eelpo.common.util.BlankUtils;
import com.eelpo.common.util.DateFormatUtils;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

/**
 * <pre>
 * 用户管理服务管理具体实现
 * </pre>
 * 
 * @author <a href="mailto:Brian@eelpo.com">汪洪州</a>
 * @since 1.0
 */
@Service
public class UserManageService implements IUserManageService {

	@Resource
	protected IUserManageDao userManageDao;

	/**
	 * (non-Javadoc)
	 * 
	 * @see com.eelpo.cmmp.uac.services.IUserManageService#getUserById(java.lang
	 *      .String)
	 */
	@Override
	public User getUserById(String id) throws ServiceException {
		TUser user = userManageDao.getUserById(id);

		if (BlankUtils.isBlank(user)) {
			throw new ServiceException("查询的用户不存在！");
		}

		return po2vo(user);
	}

	/**
	 * (non-Javadoc)
	 * 
	 * @see com.eelpo.cmmp.uac.services.IUserManageService#getUserByAccount(java
	 *      .lang.String)
	 */
	@Override
	public User getUserByAccount(String account) throws ServiceException {
		TUser user = userManageDao.getUserByAccount(account);

		if (BlankUtils.isBlank(user)) {
			throw new ServiceException("查询的用户不存在！");
		}

		return po2vo(user);
	}

	/**
	 * (non-Javadoc)
	 * 
	 * @see com.eelpo.cmmp.uac.services.IUserManageService#checkExist(java.lang.
	 *      String)
	 */
	@Override
	public boolean checkExist(String account) throws ServiceException {
		return userManageDao.checkExist(account);
	}

	/**
	 * (non-Javadoc)
	 * 
	 * @see com.eelpo.cmmp.uac.services.IUserManageService#addUser(com.eelpo.cmmp
	 *      .uac.dao.vo.User)
	 */
	@Override
	public String addUser(User user) throws ServiceException {

		// 检查帐号是否已经存在
		if (userManageDao.checkExist(user.getAccount())) {
			throw new ServiceException("用户帐号[" + user.getAccount() + "]已经存在！");
		}

		Date currentDate = new Date();
		user.setLastPasswordTime(currentDate);
		user.setLastModifiedTime(currentDate);

		return userManageDao.addUser(vo2po(user));
	}

	/**
	 * (non-Javadoc)
	 * 
	 * @see com.eelpo.cmmp.uac.services.IUserManageService#updateUser(com.eelpo
	 *      .cmmp.uac.dao.vo.User)
	 */
	@Override
	public void updateUser(User user) throws ServiceException {

		// 检查帐号是否已经存在
		if (userManageDao.checkExistByUpdate(user.getId(), user.getAccount())) {
			throw new ServiceException("用户帐号[" + user.getAccount() + "]已经存在！");
		}

		TUser tuser = userManageDao.getUserById(user.getId());

		// 判断密码是否修改
		boolean isPasswordUpdated = !PasswordEncryptor.validate(user.getPassword(), tuser.getPassword());

		// 复制非关联的值
		vo2po(tuser, user);

		// 设置修改时间
		tuser.setLastModifiedTime(DateFormatUtils.getDate());

		// 设置密码修改时间
		if (isPasswordUpdated) {
			user.setLastPasswordTime(DateFormatUtils.getDate());
		}
	}

	/**
	 * (non-Javadoc)
	 * 
	 * @see com.eelpo.cmmp.uac.services.IUserManageService#deleteUser(com.eelpo
	 *      .cmmp.uac.dao.vo.User)
	 */
	@Override
	public void deleteUser(User user) throws ServiceException {
		// TODO Auto-generated method stub

	}

	/**
	 * (non-Javadoc)
	 * 
	 * @see com.eelpo.cmmp.uac.services.IUserManageService#getUsersPaing(java.lang.String,com.eelpo
	 *      .cmmp.uac.dao.vo.User, int, int)
	 */
	@Override
	public List<User> getUsersPaing(String userId, User user, int first, int max) throws ServiceException {
		TUser tuser = userManageDao.getUserById(userId);

		if (BlankUtils.isBlank(tuser)) {
			throw new ServiceException("用户不存在！");
		}

		if (tuser.getSuperManager()) {
			return po2vo(userManageDao.getUsersPaing(user, first, max));
		} else {
			return po2vo(userManageDao.getUsersPaing(userId, user, first, max));
		}
	}

	/**
	 * (non-Javadoc)
	 * 
	 * @see com.eelpo.cmmp.uac.services.IUserManageService#getUsersCount(java.lang.String,com.eelpo
	 *      .cmmp.uac.dao.vo.User)
	 */
	@Override
	public int getUsersCount(String userId, User user) throws ServiceException {
		TUser tuser = userManageDao.getUserById(userId);

		if (BlankUtils.isBlank(tuser)) {
			throw new ServiceException("用户不存在！");
		}

		if (tuser.getSuperManager()) {
			return userManageDao.getUsersCount(user);
		} else {
			return userManageDao.getUsersCount(userId, user);
		}
	}

	/**
	 * (non-Javadoc)
	 * 
	 * @see com.eelpo.cmmp.uac.services.IUserManageService#getSuperManager()
	 */
	@Override
	public User getSuperManager() throws ServiceException {
		return po2vo(userManageDao.getSuperManager());
	}

	/**
	 * (non-Javadoc)
	 * 
	 * @see com.eelpo.cmmp.uac.services.IUserManageService#login(java.lang.String,
	 *      java.lang.String, java.lang.String)
	 */
	@Override
	public User login(String ip, String account, String password) throws ServiceException {

		TUser tuser = userManageDao.getUserByAccount(account);

		if (BlankUtils.isBlank(tuser)) {
			throw new ServiceException("用户不存在！");
		}

		User user = po2vo(tuser);

		// 检查是否允许页面登录
		if (!user.getAllowWebLogin().getValue()) {
			throw new ServiceException("用户不允许页面登录！");
		}

		// 检查用户状态
		switch (user.getStatus()) {
		case DISABLED:
			throw new ServiceException("用户已经被禁用！");
		case DELETE:
			throw new ServiceException("用户已经被删除！");
		}

		switch (user.getWebAuthMode()) {
		case IP:
			// IP过滤

			break;
		case PASSWORD:

			// 检查密码
			if (!password.equals(user.getPassword())) {
				throw new ServiceException("用户密码不正确！");
			}
			break;
		case PASSWORDIP:

			// 检查密码
			if (!password.equals(user.getPassword())) {
				throw new ServiceException("用户密码不正确！");
			}

			// IP过滤
			break;
		}

		// 设置登录时间
		user.setLoginTime(new Date());

		return user;
	}

	/**
	 * 静态转换，不包含任何关联对象的转换
	 * 
	 * @param user
	 *            用户值对象
	 * @return 返回用户实体对象
	 */
	public static TUser vo2po(TUser tuser, User user) {

		BeanUtils.copyProperties(user, tuser, new String[] { "status", "password", "superManager", "allowWebLogin", "allowInterface", "webAuthMode", "interfaceAuthMode" });

		tuser.setPassword(PasswordEncryptor.encoder(user.getPassword()));
		tuser.setStatus(Status.valueOf(user.getStatus()));
		tuser.setSuperManager(YesOrNo.valueOf(user.getSuperManager()));
		tuser.setAllowWebLogin(YesOrNo.valueOf(user.getAllowWebLogin()));
		tuser.setAllowInterface(YesOrNo.valueOf(user.getAllowInterface()));
		tuser.setWebAuthMode(AuthMode.valueOf(user.getWebAuthMode()));
		tuser.setInterfaceAuthMode(AuthMode.valueOf(user.getInterfaceAuthMode()));

		return tuser;
	}

	/**
	 * 静态转换，不包含任何关联对象的转换
	 * 
	 * @param user
	 *            用户值对象
	 * @return 返回用户实体对象
	 */
	public static TUser vo2po(User user) {
		return vo2po(new TUser(), user);
	}

	/**
	 * 静态转换，不包含任何关联对象的转换
	 * 
	 * @param tuser
	 *            用户实体对象
	 * @return 返回用户值对象
	 */
	public static User po2vo(TUser tuser) {

		User user = new User();

		BeanUtils.copyProperties(tuser, user, new String[] { "status", "password", "superManager", "allowWebLogin", "allowInterface", "webAuthMode", "interfaceAuthMode" });

		user.setPassword(PasswordEncryptor.decoder(tuser.getPassword()));
		user.setStatus(Status.valueOf(tuser.getStatus()));
		user.setAllowWebLogin(YesOrNo.valueOf(tuser.getAllowWebLogin()));
		user.setAllowInterface(YesOrNo.valueOf(tuser.getAllowInterface()));
		user.setWebAuthMode(AuthMode.valueOf(tuser.getWebAuthMode()));
		user.setInterfaceAuthMode(AuthMode.valueOf(tuser.getInterfaceAuthMode()));
		user.setSuperManager(YesOrNo.valueOf(tuser.getSuperManager()));
		return user;
	}

	/**
	 * 静态转换，不包含任何关联对象的转换
	 * 
	 * @param tusers
	 *            用户实体对象列表
	 * @return 返回用户值对象列表
	 */
	public static List<User> po2vo(List<TUser> tusers) {
		List<User> users = new ArrayList<User>();
		for (TUser tuser : tusers) {
			users.add(po2vo(tuser));
		}
		return users;
	}

}
